package com.ruyuan.twelve.juc._26;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * 动态代理
 * 自定义handler
 */
public class CustomInvocationHandler implements InvocationHandler {


    private Object target;

    /**
     * 这里对业务方法的调用是同步的，但是我们的Active Object需要的是异步
     * 所以需要引入Scheduler组件，并在invoke方法中提交给Scheduler组件
     */
    private ExecutorService executorService;

    public CustomInvocationHandler(Object target, ExecutorService executorService) {
        this.target = target;
        this.executorService = executorService;
        //注册到全局管理器中
        ExecutorManager.registry(executorService);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Future<Object> methodRequest = executorService.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                /**
                 * 这里执行真正的业务逻辑
                 */
                Thread.sleep(100);
                System.out.println("执行其他业务逻辑");
                Object invoke = method.invoke(target, args);
                return invoke;
            }
        });
        Thread.sleep(1000);
        System.out.println("提交任务完成");
        return methodRequest;
    }
}
